﻿<template>
  <section class="profile-view">
    <header>
      <h2>健康中心</h2>
      <p>维护你的身高、体重、目标等信息，我们会自动计算 BMI 与基础代谢。</p>
    </header>
    <ElRow :gutter="20">
      <ElCol :xs="24" :md="14">
        <ElCard>
          <ElForm ref="formRef" :model="form" label-width="88px" :rules="rules">
            <ElFormItem label="身高 (cm)" prop="height">
              <ElInputNumber v-model="form.height" :min="80" :max="250" :precision="1" :step="0.5" />
            </ElFormItem>
            <ElFormItem label="体重 (kg)" prop="weight">
              <ElInputNumber v-model="form.weight" :min="25" :max="200" :precision="1" :step="0.5" />
            </ElFormItem>
            <ElFormItem label="性别" prop="gender">
              <ElSelect v-model="form.gender" placeholder="请选择性别">
                <ElOption label="男" value="male" />
                <ElOption label="女" value="female" />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="年龄" prop="age">
              <ElInputNumber v-model="form.age" :min="12" :max="90" />
            </ElFormItem>
            <ElFormItem label="健康目标" prop="goal">
              <ElInput v-model="form.goal" type="textarea" :rows="3" placeholder="例如：12 周减脂 3kg / 提升 5km 配速" />
            </ElFormItem>
            <div class="form-actions">
              <ElButton @click="resetForm">重置</ElButton>
              <ElButton type="primary" :loading="saving" @click="onSubmit">保存</ElButton>
            </div>
          </ElForm>
        </ElCard>
      </ElCol>
      <ElCol :xs="24" :md="10">
        <ElCard>
          <ElDescriptions title="健康指标" :column="1" border>
            <ElDescriptionsItem label="BMI">
              <ElTag :type="bmiTagType" size="large">
                {{ profile.bmi ?? '--' }}
              </ElTag>
              <span class="metric-tip">{{ bmiLabel }}</span>
            </ElDescriptionsItem>
            <ElDescriptionsItem label="基础代谢 (BMR)">
              <strong>{{ profile.bmr ?? '--' }}</strong> kcal / 天
            </ElDescriptionsItem>
            <ElDescriptionsItem label="当前目标">
              {{ profile.goal || '记录你的健康目标' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="最近更新">
              {{ updatedAtText }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </ElCard>
      </ElCol>
    </ElRow>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import {
  ElCard,
  ElForm,
  ElFormItem,
  ElInputNumber,
  ElInput,
  ElButton,
  ElRow,
  ElCol,
  ElDescriptions,
  ElDescriptionsItem,
  ElTag,
  ElSelect,
  ElOption,
  type FormInstance,
} from "element-plus";
import { useContentStore } from "../stores/content";

const contentStore = useContentStore();
const formRef = ref<FormInstance>();
const saving = ref(false);

const profile = computed(() => contentStore.userProfile);

const form = reactive({
  height: profile.value.height,
  weight: profile.value.weight,
  gender: profile.value.gender || "",
  age: profile.value.age,
  goal: profile.value.goal,
});

const rules = {
  height: [{ required: true, message: "请输入身高", trigger: "blur" }],
  weight: [{ required: true, message: "请输入体重", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
};

const syncForm = () => {
  form.height = profile.value.height;
  form.weight = profile.value.weight;
  form.gender = profile.value.gender || "";
  form.age = profile.value.age;
  form.goal = profile.value.goal;
};

watch(profile, () => syncForm(), { immediate: true });

const bmiLabel = computed(() => {
  const bmi = profile.value.bmi ?? 0;
  if (!bmi) return "--";
  if (bmi < 18.5) return "偏瘦";
  if (bmi < 24) return "正常";
  if (bmi < 28) return "偏重";
  return "肥胖";
});

const bmiTagType = computed(() => {
  const bmi = profile.value.bmi ?? 0;
  if (!bmi) return "warning";
  if (bmi < 18.5) return "warning";
  if (bmi < 24) return "success";
  if (bmi < 28) return "warning";
  return "danger";
});

const updatedAtText = computed(() => {
  const value = (profile.value as any).updatedAt;
  if (!value) return "--";
  try {
    return new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value));
  } catch {
    return value;
  }
  return "--";
});

const resetForm = () => {
  syncForm();
};

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    saving.value = true;
    try {
      await contentStore.updateUserProfile({
        height: form.height,
        weight: form.weight,
        gender: form.gender as "male" | "female",
        age: form.age,
        goal: form.goal ?? "",
      });
    } finally {
      saving.value = false;
    }
  });
};

onMounted(async () => {
  try {
    await contentStore.fetchUserProfile();
  } catch (_) {
    // ignore
  }
});
</script>

<style scoped>
.profile-view {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

.metric-tip {
  margin-left: 8px;
  color: var(--mint-text-muted);
  font-size: 13px;
}
</style>
